package cn.js189.common.util;

import cn.js189.common.constants.Constants;
import cn.js189.common.constants.HttpStatus;
import cn.js189.common.constants.OwnerConstants;
import cn.js189.common.util.annotation.LogPlus;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
@Slf4j
public class HttpUtil {

    private HttpUtil(){/*empty*/}
    
    /**
     * post请求，带超时时间和请求头
     */
    @LogPlus(url = "#url", owner = OwnerConstants.UNIT_CREDIT)
    public static String sendPost(String url,String headJson,int timeout,String paramJson){
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader(Constants.CONTENT_TYPE, "application/json;charset=utf-8");
        if(StringUtils.isNotBlank(headJson)){
            Map<String,String> headMap = new Gson().fromJson(headJson, new TypeToken<Map<String, String>>() {}.getType());
            for(Map.Entry<String, String> entry:headMap.entrySet()){
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpPost.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(paramJson, HttpStatus.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response=httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result= EntityUtils.toString(response.getEntity(),HttpStatus.UTF_ENCODING);
            }
        } catch (Exception e) {
            log.error("请求出错，url:"+url+",errormsg:"+e.getMessage(),e);
        }finally {
            long callEnd = System.currentTimeMillis();
            log.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }

    public static String postJSONHttpProxy(String url, String param, int timeout, String switchStr) {
        log.info("请求url{}：,switchStr:{}",url,switchStr);
        log.info("入参：{}",param);
        HttpClientBuilder builder = HttpClientBuilder.create();
        try(CloseableHttpClient client = builder.build()) {
            HttpPost post = new HttpPost(url);
            //4.3之后，超时时间用此方法设置，早期方法会报过时
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
            post.setConfig(requestConfig);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            StringEntity entity = new StringEntity(param);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                log.info("回参：{}",result);
                return result;
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        return null;
    }
    public static String postWebServiceHttpProxy(String url, String param, int timeout, String switchStr,String encodeStr) {
        log.info("请求url{}：,switchStr:{}",url,switchStr);
        log.info("入参：{}",param);
        HttpClientBuilder builder = HttpClientBuilder.create();
        try(CloseableHttpClient client = builder.build()) {
            HttpPost post = new HttpPost(url);
            //4.3之后，超时时间用此方法设置，早期方法会报过时
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
            post.setConfig(requestConfig);
            post.setHeader("Content-Type", "text/xml");
            post.setHeader("SOAPAction", "action");
            StringEntity entity = new StringEntity(param);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity(), encodeStr);
                log.info("回参：{}",result);
                return result;
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        return null;
    }
}
